import React, { PureComponent } from 'react';
import { Table, Button, Input,  Popconfirm, Select } from 'antd';
import styles from './index.less';
import { PlusOutlined } from '@ant-design/icons';
import { getDicByKey } from '@/support/common';
import PropTypes from 'prop-types';
const { Option } = Select;
import { connect } from 'dva';

@connect((state: any) => ({
  goodAdd: state.goodAdd,
}))
export default class TableForm extends PureComponent<any, any>  {
  static contextTypes = {
    dicData: PropTypes.any,
  };
  constructor(props:any) {
    super(props);

    this.state = {
      data: [],
      attributeList: [],
      oldList:[],//保存原始的附属属性数据
      maxSid: 0,//0
    };
  }
  componentDidMount() {
    this.props.onRef(this);
    const { goodsInfo=[] } = this.props;
    const {attributeList} =this.props;
    const checkedValue = goodsInfo.map((item:any)=>{
      return item.skuAttributeCode
    })
    const newOption = [...attributeList]
          for (let i in goodsInfo) {
            goodsInfo[i].key = Number(i)
            goodsInfo[i].editable = true
        }
    this.setState({
      oldList: attributeList,
      data:  goodsInfo,
      maxSid:  goodsInfo.length - 1,
      attributeList: newOption.filter(item => !checkedValue.includes(item.skuAttributeCode))
    })
    // }
  }
  componentWillMount() {

  }
  getRowByKey(key:any) {
    return this.state.data.filter((item:any) => item.key === key)[0];
  }
  //删除条目
  remove(key:any, keyIndex:any) {
    if (!key) {
      const restDate = this.state.data.filter((item:any) => item.key !== keyIndex)
      this.setState({ data: [...restDate] });
       //刷新附属属性名称数据中已被选中的
    const{oldList}=this.state;
    const checkedValue = restDate.map((item:any)=>{
      return item.sid
    })
    const newOption = [...oldList]
    this.setState({ attributeList: newOption.filter(item => !checkedValue.includes(item.sid))});
      return;
    }
    const newData = this.state.data.filter((item:any) => item.sid !== key);
    this.setState({ data: newData });
    //刷新附属属性名称数据中已被选中的
    const{oldList}=this.state;
    const checkedValue = newData.map((item:any)=>{
      return item.sid
    })
    const newOption = [...oldList]
    this.setState({ attributeList: newOption.filter(item => !checkedValue.includes(item.sid))});
  }
  
  newMember = () => {
    const newData = [...this.state.data];
    newData.push({
      sid: '',
      key: this.state.maxSid + 1,
      editable: true,
      isNew: true,
    });
    this.setState({ data: newData, maxSid: this.state.maxSid + 1 });
  }
  handleFieldChange(e:any, fieldName:any, key:any) {
    const newData = [...this.state.data];
    const target = this.getRowByKey(key);
    if (target) {
      target[fieldName] = e.target.value;
      this.setState({ data: newData });
    }
  }
   handleNameChange(e:any, fieldName:any, record:any) {
    const{data,oldList}=this.state;
    const newData = JSON.parse(JSON.stringify(data));
    const key = record.key;
    const target = newData.filter((item:any) => item.key === key)[0];
    const attrItem = this.state.attributeList.filter((item:any) => item.skuAttributeCode ===fieldName)
    if (target) {
      target['sid'] = fieldName;
      target['skuAttributeName'] = attrItem[0]?.skuAttributeName;
      target['skuAttributeCode'] = attrItem[0]?.skuAttributeCode;
      target['unit'] = attrItem[0]?.unit;
      this.setState({ data: newData });
    }
    //删除附属属性名称数据中已被选中的
    const checkedValue = newData.map((item:any)=>{
      return item.skuAttributeCode
    })
    const newOption = [...oldList]
    this.setState({ attributeList: newOption.filter(item => !checkedValue.includes(item.skuAttributeCode))});
  }
  //将编辑后的附属属性列表返回给父组件
  getData = () =>{
    const {data}=this.state;
    return data;
  }
  render() {
    // 行选择对象表示对行选择的需要
    const options = this.state.attributeList?.map((d:any) =>
      <Option key={d.skuAttributeCode}>{d.skuAttributeName}</Option>);
    const columns = [
      {
        title: "序号",
        render: (text:any, record:any, index:any) => index + 1,
      },
      {
      title: '附属属性名称',
      dataIndex: 'skuAttributeName',
      key: 'skuAttributeName',
      render: (text:any, record:any) => {
        if (record.editable) {
          return (
            <Select
              getPopupContainer={triggerNode => triggerNode.parentNode}
              defaultValue={text}
              style={{ width: 260 }}
              autoFocus
              onChange={(value, e) => this.handleNameChange(e, value, record)}
              placeholder="请选择附属属性"
            >
              {options}
            </Select>
          );
        }
        return text;
      },
    }, {
      title: '附属属性代码',
      dataIndex: 'skuAttributeCode',
    }, {
      title: '单位',
      dataIndex: 'unit',
        render: (text:any) => {
          if (text) {
            return getDicByKey(this.context.dicData, 'unit', text) || text;
          } else {
            return text;
          }
        },
    }, {
      title: '附属属性值',
      dataIndex: 'skuAttributeValue',
      key: 'skuAttributeValue',
      render: (text:any, record:any) => {
        if (record.editable) {
          return (
            <Input
              value={text}
              style={{ width: 300 }}
              onChange={e => this.handleFieldChange(e, 'skuAttributeValue', record.key)}
              placeholder="附属属性值"
              maxLength={100}
            />
          );
        }
        return text;
      },
    },{
      title: '操作',
      key: 'action',
      render: (text:any, record:any) => {
       return (
        <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record.sid, record.key)}>
            <a>删除</a>
        </Popconfirm>
       )
      },
    }];

    return (
      <div>
        <Table
          bordered={true}
          columns={columns}
          rowKey={record => record.key}
          dataSource={this.state.data}
          pagination={false}
          rowClassName={() => styles["editable-row"]}
        />
        <Button
          style={{ width: '100%', marginTop: 16, marginBottom: 8 }}
          type="dashed"
          onClick={this.newMember}
          icon={<PlusOutlined />}
        >
          新建条目
        </Button>
      </div>
    );
  }
}
